<template>
  <div :style="{ display: 'inline-flex', justifyContent: 'center', alignItems: 'center' }">
    <template v-for="item in options">
      <template v-if="values.includes(String(item.value))">
        <span
          v-if="item.colorType === 'default' || item.colorType === ''"
          :key="item.value"
          :class="item.cssClass"
          >{{ item.label + ' ' }}</span
        >
        <el-tag
          v-else
          :disable-transitions="true"
          :key="item.value + ''"
          :type="item.colorType === 'primary' ? undefined : item.colorType"
          :class="item.cssClass"
        >
          {{ item.label }}
        </el-tag>
      </template>
    </template>
    <template v-if="unmatch && showUnmatch">
      {{ handleUnmatch(unmatchValues) }}
    </template>
  </div>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes'
import { DictDataType } from '@/utils/dict'

const props = defineProps({
  options: {
    type: Array as PropType<DictDataType[]>,
    required: true
  },
  value: propTypes.oneOfType([String, Number, Boolean, Array]),
  separator: propTypes.string.def(','),
  // 数值类型的字典值，默认将0值视为空值，未匹配到选项时，对其进行展示忽略
  ignoreZero: propTypes.bool.def(true),
  // 是否显示未匹配到的value
  showUnmatch: propTypes.bool.def(true)
})

const unmatchValues = ref<string[]>([])

const values = computed(() => {
  if (props.value === null || props.value === undefined || props.value === '') {
    return []
  }
  return Array.isArray(props.value)
    ? props.value.map((val) => val + '')
    : String(props.value).split(props.separator)
})

const unmatch = computed(() => {
  unmatchValues.value = []
  if (props.value === null || props.value === undefined || props.value === '') {
    return false
  }
  let unmatch = false
  unref(values).forEach((val) => {
    if (!props.options.some((opt) => String(opt.value) === val)) {
      if (!props.ignoreZero || props.value !== 0) {
        unmatchValues.value.push(val)
        unmatch = true
      }
    }
  })
  return unmatch
})

const handleUnmatch = (array) => {
  if (!array?.length) {
    return ''
  }
  return array.reduce((acc, val) => {
    return acc + ' ' + val
  })
}
</script>

<style scoped lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
